package tk.winshu.shortestpath.util;

import tk.winshu.shortestpath.model.Node;

import java.util.List;

/**
 * 导出工具类
 *
 * @author Jason Krebs
 * @date 2015年2月7日
 */
public class ExportUtil {

    private static final String JSON_FORMAT = "{\"node\":[%s],\"line\":[%s]}";
    private static final String LINE_FORMAT = "{\"start\":%d,\"end\":%d}";
    private static final String NODE_FORMAT = "{\"index\":%d,\"location\":{\"x\":%.2f,\"y\":%.2f}}";
    private static final String COMMA = ",";

    /**
     * 导出
     */
    public static void exportTo(List<Node> nodes, String path) {
        String data = String.format(JSON_FORMAT, buildNodes(nodes), buildLines(nodes));
        FileUtil.saveTo(path, data);
    }

    /**
     * 连线信息
     */
    private static String buildLines(List<Node> nodes) {
        StringBuilder sb = new StringBuilder();
        for (Node start : nodes) {
            for (Node end : start.getEndNodes()) {
                sb.append(formatLineString(start, end)).append(COMMA);
            }
        }
        if (sb.length() > 0) {
            sb.delete(sb.length() - COMMA.length(), sb.length());
        }
        return sb.toString();
    }

    /**
     * 节点信息
     */
    private static String buildNodes(List<Node> nodes) {
        StringBuilder sb = new StringBuilder();
        for (Node node : nodes) {
            sb.append(formatNodeString(node)).append(COMMA);
        }
        if (sb.length() > 0) {
            sb.delete(sb.length() - COMMA.length(), sb.length());
        }
        return sb.toString();
    }

    /**
     * 格式化连线字符串
     */
    private static String formatLineString(Node start, Node end) {
        return String.format(LINE_FORMAT, start.getIndex(), end.getIndex());
    }

    /**
     * 格式化节点字符串
     */
    private static String formatNodeString(Node node) {
        return String.format(NODE_FORMAT, node.getIndex(), node.getLocation().getX(), node.getLocation().getY());
    }

}
